import React, {Component} from 'react'
import {Alert, Button, Modal, Form, Input, Select, Table, Popover} from 'antd'
import {connect} from 'react-redux'
import {messages} from "share/common";
import AccountSetServer from 'containers/supplier-management/accounting-settings/account-setting-server'

const FormItem = Form.Item;
const Option = Select.Option;

@Form.create()
class TabOfflineConsumer extends Component {

  constructor(props) {
    super(props);
    this.businessType = [ // 业务类型
      {label: messages('supplier.key443')/*机票*/, value: 'AIR'},
      {label: messages('supplier.key444')/*酒店*/, value: 'HOTEL'},
    ]
    this.columns = [
      {title: messages('common.sequence')/*序号*/, dataIndex: 'index', width: 80},
      {title: messages('supplier.key605')/*消费商名称*/, dataIndex: 'vendorCn'},
      {title: messages('supplier.key606')/*消费商导入code*/, dataIndex: 'vendor'},
      {title: messages('supplier.key607')/*业务类型*/, dataIndex: 'vendorType'},
      {
        title: messages('supplier.key608')/*映射费用*/,
        dataIndex: 'expenseTypeConfigList',
        render: (value) => {
          const str = [];
          value.map(item => {
            if(item.expenseTypeName) {
              str.push(item.expenseTypeName);
            }
          });
          return (
            <Popover placement="topLeft" content={str.join(', ')}>
              {str.join(', ')}
            </Popover>
          )
        }
      },
      {
        title: messages('common.operation')/*操作*/,
        dataIndex: 'index5',
        render: (value, record) => {
          return (
            <a onClick={() => this.toEditSetting(record)}>{messages('common.edit')/*编辑*/}</a>
          )
        }
      },
    ];
    this.params = {
      channel: "hly-admin",
      tenantId: props.tenant.id,
      page: 1,
      size: 10,
    }
    this.state = {
      isEdit: false,// 是否是编辑(新增和编辑两种状态)
      showModal: false,// 是否弹出编辑框
      pagination: {
        current: 1,
        page: 1,
        size: 10,
        total: 0,
      },
      loading: false,
      data: [],
      editData: {},// 被编辑数据
      setOfBooks: [],// 账套数据
    }
  }

  componentWillMount() {
    AccountSetServer(this).getAccountSettingDefault(this.params).then(res => {
      const {pagination} = this.state;
      pagination.total = res.data.total;
      this.setState({
        data: this.addIndex(res.data.invoicePushConfigs),
        pagination,
        setOfBooks: res.data.expenseTypeConfigList
      })
    })
  }

  /**
   * 添加序号
   * @param data
   */
  addIndex = (data = []) => {
    const {current, size} = this.state.pagination;
    data = data.map((item, index) => {
      item.index = size * (current - 1) + (index + 1);
      return item;
    });
    return data;
  }

  // 更新当前页面数据
  updateThisPageData = () => {
    AccountSetServer(this).getAccountSettingDefault(this.params).then(res => {
      const {pagination} = this.state;
      pagination.total = res.data.total;
      this.setState({
        data: this.addIndex(res.data.invoicePushConfigs),
        pagination,
      })
    })
  }

  /**
   * 账套表单被点击时初始化费用类型
   * @param id   被点击的账套 ID 值
   * @param index  被点击的账套是第几个账套
   */
  onFocusSelect = (id, index) => {
    const {setOfBooks, isEdit, editData} = this.state;
    const {expenseTypeConfigList} = editData;
    if (!setOfBooks[index].expenseData && !isEdit) {// 新建时第index账套内的费用类型未加载
      AccountSetServer(this).getExpense(id).then(res => {
        setOfBooks[index].expenseData = this.filterExpenseData(res.data);
        this.setState({setOfBooks});
      })
    } else if (isEdit) {// 编辑时
      // 被编辑的第index个账套费用已加载过 且 该账套与正在被编辑的账套id相同 且 被编辑的账套内的费用未加载过
      if (setOfBooks[index].expenseData && setOfBooks[index].setOfBooks === id && !expenseTypeConfigList[index].expenseData) {
        expenseTypeConfigList[index].expenseData = setOfBooks[index].expenseData;
        this.setState({editData}, this.props.form.resetFields);
      } else if (!expenseTypeConfigList[index].expenseData) {// 被编辑的账套内的费用未被初始化
        AccountSetServer(this).getExpense(id).then(res => {
          expenseTypeConfigList[index].expenseData = this.filterExpenseData(res.data);
          this.setState({editData});
        })
      }
    }
  }

  // 后端要求根据账套ID查询费用时，要对结果过滤掉 yangzhao=> messageKey: "yangzhao"
  filterExpenseData(data=[]){
    const arr = data.filter((item) => {
      if(item.messageKey === 'yangzhao'){
        return false;
      }else{
        return true;
      }
    });
    return arr;
  }

  /**
   * 表格监听-分页
   * @param pagination
   */
  onTableChange = (pagination) => {
    this.setState({pagination}, () => {
      this.params.page = pagination.current;
      this.updateThisPageData();
    });
  }

  // 新增按钮监听
  addNewSetting = () => {
    this.setState({showModal: true})
  }

  /**
   * 编辑消费商
   * @param record 消费商实例
   */
  toEditSetting = (record) => {
    this.setState({showModal: true, isEdit: true, editData: record}, () => {
      this.props.form.resetFields();
    });
  }

  // 编辑或者新增完成 保存（这块逻辑没有后端支持真是费脑子）
  onEditEndOk = () => {
    const saveParams = {
      "channel": "hly-admin",
      "configList": [],
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      const editParams = {
        "vendor": values.vendor || "",
        "vendorCn": values.vendorCn || "",
        "tenantId": this.props.tenant.id,
        "vendorType": values.vendorType || "",
        "expenseTypeConfigList": []
      }
      const {setOfBooks, isEdit, editData} = this.state;
      setOfBooks.map(item => {
        let exp = values[`SET_OF_BOOK${item.setOfBooks}`] || '';
        let expense = {};
        if(isEdit && !exp.includes('+')){
          const {expenseTypeConfigList} = editData;
          expenseTypeConfigList.map(expItem => {
            if(expItem.expenseTypeName === exp){
              expense = {
                "setOfBooks": item.setOfBooks,
                "setOfBooksName": item.setOfBooksName,
                "expenseType": expItem.expenseType || "",
                "expenseTypeName": exp || "",
              };
            }
          });
        }else{
          exp = exp.split('+');
          expense = {
            "setOfBooks": item.setOfBooks,
            "setOfBooksName": item.setOfBooksName,
            "expenseType": exp[0] || "",
            "expenseTypeName": exp[1] || "",
          };
        }
        editParams.expenseTypeConfigList.push(expense)
      });
      saveParams.configList.push(editParams);
      AccountSetServer(this).saveAccountSettingDefault(saveParams).then(res => {
        this.params.page = 1;
        this.updateThisPageData();
      });
      this.onEditEndCancel();
    })
  }

  // 编辑或者新增取消
  onEditEndCancel = () => {
    this.setState({showModal: false, isEdit: false, editData: {}});
    this.props.form.resetFields();
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    const {pagination, data, isEdit, showModal, loading, setOfBooks, editData} = this.state;
    const formLayout = {
      wrapperCol: {span: 14},
      labelCol: {span: 8}
    }
    const showSetOfBooks = isEdit ? editData.expenseTypeConfigList : setOfBooks;
    return (
      <div style={{marginTop: 16}}>
        <Alert type='info' message={messages('supplier.key609')/*可在此处设置线下消费商code，并设置费用映射关系*/} showIcon/>
        <Button
          style={{margin: '12px 0'}}
          type='primary'
          onClick={this.addNewSetting}
        >
          {messages('supplier.key203')/*新增*/}
        </Button>
        <Table
          bordered
          rowKey='vendor'
          dataSource={data}
          loading={loading}
          columns={this.columns}
          onChange={this.onTableChange}
          pagination={pagination}
        />
        <Modal
          title={isEdit ? messages('common.edit')/*编辑*/ : messages('supplier.key610')/*新增消费商*/}
          visible={showModal}
          onOk={this.onEditEndOk}
          onCancel={this.onEditEndCancel}
          okText={messages('common.save')/*保存*/}
        >
          <Form>
            <FormItem label={messages('supplier.key611')/*消费商code*/} {...formLayout}>
              {
                getFieldDecorator('vendor', {
                  initialValue: editData.vendor || '',
                  rules: [
                    {
                      required: true,
                      message: messages('supplier.key612')/*必填*/
                    }
                  ]
                })(
                  <Input disabled={isEdit} placeholder={messages('common.please.input')/*请输入*/}/>
                )
              }
            </FormItem>
            <FormItem label={messages('supplier.key605')/*消费商名称*/} {...formLayout}>
              {
                getFieldDecorator('vendorCn', {
                  initialValue: editData.vendorCn || '',
                  rules: [
                    {
                      required: true,
                      message: messages('supplier.key612')/*必填*/
                    }
                  ]
                })(
                  <Input placeholder={messages('common.please.input')/*请输入*/}/>
                )
              }
            </FormItem>
            <FormItem label={messages('supplier.key607')/*业务类型*/} {...formLayout}>
              {
                getFieldDecorator('vendorType', {
                  initialValue: editData.vendorType || '',
                  rules: [
                    {
                      required: true,
                      message: messages('supplier.key612')/*必填*/
                    }
                  ]
                })(
                  <Select placeholder={messages('common.please.select')}>
                    {
                      this.businessType.map(item => {
                        return (
                          <Option value={item.value}>{item.label}</Option>
                        )
                      })
                    }
                  </Select>
                )
              }
            </FormItem>
            <Alert type='info' message={messages('supplier.key613')/*可以给每个账套设置映射的费用类型*/} showIcon/>
            <br/>
            {
              showSetOfBooks.map((item, index) => {
                return (
                  <FormItem label={item.setOfBooksName} {...formLayout}>
                    {
                      getFieldDecorator(`SET_OF_BOOK${item.setOfBooks}`, {
                        initialValue: item.expenseTypeName || '',
                      })(
                        <Select
                          showSearch
                          onFocus={() => this.onFocusSelect(item.setOfBooks, index)}
                          placeholder={messages('common.please.select')}
                          optionFilterProp="children"
                          filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                        >
                          {
                            item.expenseData && item.expenseData.map(item => {
                              return (
                                <Option value={`${item.code}+${item.name}`}>{item.name}</Option>
                              )
                            })
                          }
                        </Select>
                      )
                    }
                  </FormItem>
                )
              })
            }
          </Form>
        </Modal>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  }
}

export default connect(mapStateToProps)(TabOfflineConsumer);
